package com.qire.common.inject;

import com.qire.antsbinder.utils.TypeUtils;
import com.qire.antsbinder.viewModel.ViewModelFactory;
import com.qire.antsrouter.card.FloorCard;
import com.qire.antsrouter.inject.Injector;
import com.qire.common.support.base.BaseActivity;
import com.qire.common.support.base.BaseViewModel;
import com.qire.common.support.base.ProxyViewModel;

import java.lang.reflect.Field;

import androidx.databinding.ViewDataBinding;

/**
 * 统一ViewModel注入器
 */
public class ViewModelInjector implements Injector<FloorCard, BaseActivity> {

    @Override
    public void inject(Field field, FloorCard postcard, BaseActivity activity) {

        // 创建ViewModel
        Class<? extends BaseViewModel> viewModelClass = (Class<? extends BaseViewModel>)field.getType();
        BaseViewModel viewModel = ViewModelFactory.crate(activity, viewModelClass);

        // 注入创建的ViewModel到目标
        try {
            field.setAccessible(true);
            field.set(activity,viewModel);
            field.setAccessible(false);
        } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }


        // 绑定并获取bindView
        ViewDataBinding bindView = activity.viewDataBinder();

        // 绑定到ViewDataBind的变量ID
        int variableId;
        // 具体绑定的对象
        Object proxy;

        // 使用ProxyViewModel定义的ViewModel
        if(ProxyViewModel.class.isInstance(viewModel)) {
            // 获取在字段上申明的接口类型
            Class<?> viewModelProxyClass = (Class<?>) TypeUtils.getFieldActualGenericType(field,0);
            variableId = getVariableId(viewModelProxyClass);
            proxy = viewModel.buildProxy(viewModelProxyClass);
        } else {
            if((variableId = viewModel.getVariableId()) == BaseViewModel.INVALID_ID) {
                Class<?> viewModelProxyClass = (Class<?>) TypeUtils.getSuperclassTypeParameter(viewModelClass,0);
                variableId = getVariableId(viewModelProxyClass);
            }
            proxy = viewModel.buildProxy();
        }

        // 构建ViewModel的代理类
        bindView.setVariable(variableId, proxy);

    }

    /**
     * 提取variableId从proxyClass中获取
     * @param proxyClass
     * @return variableId
     */
    private int getVariableId(Class<?> proxyClass) {
        try {
            Field variableIdField = proxyClass.getDeclaredField("variableId");
            return (int) variableIdField.get(proxyClass);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return 0;
    }

}
